package com.qf.springcloud.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zjw
 * @description 限流过滤器
 * @date 2021/11/12 9:57
 */
@Component
public class RateLimitFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1500;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }


    private RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    public Object run() throws ZuulException {
        // 从令牌桶中获取一个令牌
        System.out.println(new Date());
        if (rateLimiter.tryAcquire()) {
            System.out.println("获取令牌成功，正常放行！");
        }else{
            System.out.println("没有门禁卡，门口保安不让进！");
        }
        return null;
    }
}
